/*
 Xern Entity Relocation Network
 Copyright (C) 2010-2011 Ronie Salgado <roniesalg@gmail.com>

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

#include "Xern/IClientModule.hpp"
#include "Xern/IMetaverseNodeFactory.hpp"
#include "Xern/IPhysicsEngine.hpp"
#include "Xern/Engine.hpp"
#include "Xern/Exceptions.hpp"
#include "Xern/Log.hpp"
#include "Xern/PluginRegistrator.hpp"
#include "Xern/RegionLoader.hpp"
#include "Xern/WorldManager.hpp"

#include "ServerModule.hpp"

namespace XernServer
{
	static PluginRegistrator<ServerModule>
	serverPlugin("Server", "XernServer");

	ServerModule::ServerModule()
	{
	}

	ServerModule::~ServerModule()
	{
	}

	void ServerModule::Initialize()
	{
		Engine &engine = Engine::Get();

		// Create the server console.
		console.reset(new Console());

		// Register it with the master console.
		boost::shared_ptr<Console> masterConsole =
			boost::dynamic_pointer_cast<Console> (engine.GetMasterConsole());
		masterConsole->RegisterSubConsole(console);

		// Register the console commands.
		console->RegisterCommand(ConsoleCommand(&ServerModule::MapCommand, this,
				"map", "loads and run a map"));
		console->RegisterCommand(ConsoleCommand(&ServerModule::ListenCommand, this,
				"listen", "Starts the metaverse server"));

		// Initialize the physics engine.
		boost::shared_ptr<IPhysicsEngine> physics = engine.GetPhysicsEngine();
		physics->Initialize();

		// Run the server script.
		try
		{
			engine.GetScriptEngine()->RunScript("media/scripts/server/server.nut");
		}
		catch(XernException &e)
		{
			LogConsole->Error("Failed to run the server script: %s.", e.what());
		}
	}

	void ServerModule::Shutdown()
	{
		Engine &engine = Engine::Get();

		// Shutdown the metaverse.
		if(metaverseServer)
			metaverseServer->Shutdown();

		// Shutdown the physics engine.
		boost::shared_ptr<IPhysicsEngine> physics = engine.GetPhysicsEngine();
		physics->Shutdown();

		// Unregister the server console.
		boost::shared_ptr<Console> masterConsole =
				boost::dynamic_pointer_cast<Console> (engine.GetMasterConsole());
		//masterConsole->UnregisterSubConsole(console);

		// Destroy the server console.
		console.reset();
	}

	int ServerModule::MapCommand(int argc, const char *argv[])
	{
		if(argc < 2)
		{
			LogConsole->Usage("map <mapname>");
			return -1;
		}

		// Print a loading message
		LogConsole->Notify("Loading map '%s'", argv[1]);

		// Notify the local client
		boost::shared_ptr<IClientModule> client = Engine::Get().GetClientModule();
		if(client)
			client->BeginRegionLoad();

		// Clear the world.
		boost::shared_ptr<WorldManager> world = Engine::Get().GetWorldManager();
		world->Clear();

		// Create the region loader.
		boost::shared_ptr<RegionLoader> loader(new RegionLoader());
		boost::shared_ptr<Region> region;

		try
		{
			// Load the region
			region = loader->LoadFromResource(argv[1], "Maps");
		}
		catch(XernException &e)
		{
			LogConsole->Error("Failed to load region: %s", e.what());
			return 0;
		}

		// Add the region to the world.
		world->AddChild(region);

		// Notify that the region was loaded
		LogConsole->Notify("Region '%s' loaded", argv[1]);

		// Spawn the region.
		region->Spawn();

		// Notify the local client.
		if(client)
			client->RegionLoaded(region);

		return 0;
	}

	int ServerModule::ListenCommand(int argc, const char *argv[])
	{
		int listenPort = 9654;
		std::string protocol = "Xern";

		// Parse the command line.
		for(int i = 1; i < argc; i++)
		{
			if(!strcmp(argv[i], "-p"))
			{
				protocol = argv[++i];
			}
			else
			{
				listenPort = atoi(argv[i]);
			}
		}

		// Find the protocol.
		boost::shared_ptr<IMetaverseNodeFactory> nodeFactory
		= Engine::Get().GetPluginRegistry()
			->QueryInterface<IMetaverseNodeFactory> ("MetaverseProtocol", protocol);
		if(!nodeFactory)
		{
			LogConsole->Error("Failed to query '%s' protocol plugin.", protocol.c_str());
			return -1;
		}

		// Shutdown the old server.
		if(metaverseServer)
			metaverseServer->Shutdown();

		// Create the new server.
		metaverseServer = nodeFactory->CreateServer();

		// Set the listening port.
		metaverseServer->SetPort(listenPort);

		// Initialize the server.
		metaverseServer->Initialize();

		return 0;
	}

	bool ServerModule::Frame(float delta)
	{
		// Perform physicss.
		boost::shared_ptr<IPhysicsEngine> physics = Engine::Get().GetPhysicsEngine();
		physics->Frame(delta);

		// Perform entity thinking.
		boost::shared_ptr<WorldManager> world = Engine::Get().GetWorldManager();
		world->Frame(delta);

		// Metaverse networking
		if(metaverseServer)
			metaverseServer->Frame(delta);

		return true;
	}

	boost::shared_ptr<Entity> ServerModule::CreatePlayerController(boost::shared_ptr<Region> region)
	{
		boost::shared_ptr<Entity> ret;
		if(!region)
			return ret;

		// Find the start point.
		boost::shared_ptr<Entity> point = region->FindChildByClassName("info.player.start");
		if(!point)
		{
			printf("Failed to find start point\n");
			return ret;
		}

		// Get the world manager.
		boost::shared_ptr<WorldManager> world = Engine::Get().GetWorldManager();

		// Create the player.
		ret = world->CreateEntity("player.human");
		if(!ret)
			return ret;

		// Add the player into the region.
		region->AddChild(ret);

		// Set the player position.
		ret->SetTransform(point->GetWorldTransform());

		// Spawn the player.
		ret->Spawn();

		// Return the player.
		return ret;
	}
}; // namespace XernServer
